<?php
namespace Admin\Controller;

use Admin\Model\AdminModel;
use Admin\Model\AuthGroupModel;

class UserController extends AdminController {
    public function index(){
        // 获取所有用户
        $list = D('Admin')->get(['type'=>['in',[0,1]]]);
        $page = D('Admin')->getPage();

        int_to_string($list,['status'=>[1=>'正常',0=>'禁用']]);

        // 获得所有用户组,id为索引
        $groups = M('AuthGroup')->where( array('status'=>array('egt','0'),'module'=>'admin','type'=>AuthGroupModel::TYPE_ADMIN) )
            ->getfield('id,id,title,rules');

        $group_access = D('AuthGroupAccess')->getField('uid,uid,group_id');

        $this->assign('page',$page);
        $this->assign('list',$list);
        $this->assign('groups',$groups);
        $this->assign('group_access',$group_access);
        $this->display();
    }


    public function add($username = '', $password = '111111', $repassword = '', $email = '', $nickname=''){
        if(IS_POST){

            /* 调用注册接口注册用户 */
            $User   =   new AdminModel();
            $uid    =   $User->register($username, $nickname, $password, $email);
            if(0 < $uid){ //注册成功
                $this->success('用户添加成功！',U('index'));
            } else { //注册失败，显示错误信息
                $this->error($User->getError());
            }
        }else{
            $this->assign('title','新增用户');
            $this->assign('info',['status'=>1]);
            $this->display('edit');
        }
    }

    public function edit($uid) {
        if (!$uid) {
            $this->error('无用户ID');
            exit;
        }

        // 获取用户信息
        $info = M('Admin')->where(array('uid'=>$uid))->find();

        if (IS_POST) {
            $data = [
                'username' => I('post.username',''),
                'nickname' => I('post.nickname',''),
                'password' => I('post.password',''),
                'status'   => I('post.status',0),
            ];
            if ($info['username'] === $data['username']) {
                unset($data['username']);
            }
            if ($info['nickname'] === $data['nickname']) {
                unset($data['nickname']);
            }
            if (!$data['password']) {
                unset($data['password']);
            }

            $User = new AdminModel();
            if (($data = $User->create($data)) && $User->where(['uid'=>$uid])->save($data)) {
                $this->success('修改用户成功');
            } else {
                $this->error('修改用户失败 '.$User->getError());
            }
        } else if (IS_GET) {

            $this->assign('info', $info);
            $this->display('edit');
        }
    }

    public function delete($uid = null){
        if (!$uid) {
            $this->error('无UID');
        }
        $User = new AdminModel();
        if ($User->remove($uid)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败 '. $User->getError());
        }
    }
}